<?php


namespace app\shop\controller\admin;


use app\shop\controller\BaseAdminController;
use app\shop\model\user\UserModel;
use app\shop\service\user\UserService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\App;
use think\Request;

class DesignController extends BaseAdminController
{
    public function __construct(App $app)
    {
        $this->model = new UserModel();
        $this->search = $this->setSearch($app->request);
        $this->sort = $this->setSort();
        $this->withModel = ['role', 'department'];
        parent::__construct($app);
    }

    function setSearch(Request $request)
    {
        $where = [];
        $where[] = ['role_id', '=', $request->param('role_id')];
        return [
            'like' => ['realname', 'mobile'],
            'custom' => $where
        ];
    }

    function setSort()
    {
        return [
            'role_name' => 'role_id'
        ];
    }

    /**
     * 会员列表
     * @return \think\response\Json
     */
    public function getList()
    {
        try {
            $list = parent::getList()->toArray();
            foreach ($list['data'] as &$v) {
                $v['create_code_time'] = $v['morning_start_work_time'] > 0 ? date('Y-m-d', $v['morning_start_work_time']) : '';
                $v['morning_start_work_time'] = $v['morning_start_work_time'] > 0 ? date('H:i', $v['morning_start_work_time']) : '';
                $v['afternoon_end_work_time'] = $v['afternoon_end_work_time'] > 0 ? date('H:i', $v['afternoon_end_work_time']) : '';
                $v['last_refresh_code_time'] = date('Y-m-d H:i:s');
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 生成登录码
     * @return \think\response\Json
     */
    public function generateCode()
    {
        try {
            $where = [];
            $id = $this->request->param('id', 0);
            $roleId = $this->request->param('role_id', 0);
            $startTime = $this->request->param('start_time', 0);
            if (!$startTime) {
                throw new \Exception('请设置上班时间');
            }
            $startTime = strtotime(date('Y-m-d ' . $startTime));

            $endTime1 = $this->request->param('end_time1', 0);
            if (!$startTime) {
                throw new \Exception('请设置下班时间');
            }
            $endTime1 = strtotime(date('Y-m-d ' . $endTime1));
            if ($id) {
                $where[] = ['user_id', '=', $id];
            } else {
                $where[] = ['role_id', '=', $roleId];
            }
            $idArr = UserModel::where($where)->column('user_id');
            UserService::generateCode($idArr, $startTime, $endTime1);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 下载
     * @return \think\response\Json
     */
    public function download()
    {
        try {
            $where = $this->searchWhere;
            $list = UserModel::where($where)
                ->order('user_id', 'desc')
                ->select()
                ->toArray();
            $spreadsheet = new Spreadsheet();
            $worksheet = $spreadsheet->getActiveSheet();
            $worksheet->getDefaultColumnDimension()->setWidth(20);
            $worksheet->setCellValue("A1", 'ID');
            $worksheet->setCellValue("B1", '姓名');
            $worksheet->setCellValue("C1", '手机号');
            $worksheet->setCellValue("D1", '登录码');
            $worksheet->setCellValue("E1", '上午上班时间');
            $worksheet->setCellValue("F1", '上午下班时间');
            $worksheet->setCellValue("G1", '下午上班时间');
            $worksheet->setCellValue("H1", '下午下班时间');
            $i = 2;
            foreach ($list as $v) {
                $startTime = $v['morning_start_work_time'] > 0 ? date('m-d H:i', $v['morning_start_work_time']) : '';
                $endTime = $v['morning_end_work_time'] > 0 ? date('m-d H:i', $v['morning_end_work_time']) : '';
                $startTime1 = $v['afternoon_start_work_time'] > 0 ? date('m-d H:i', $v['afternoon_start_work_time']) : '';
                $endTime2 = $v['afternoon_end_work_time'] > 0 ? date('m-d H:i', $v['afternoon_end_work_time']) : '';
                $worksheet->setCellValue("A" . $i, $v['user_id']);
                $worksheet->setCellValue("B" . $i, $v['realname']);
                $worksheet->setCellValue("C" . $i, $v['mobile']);
                $worksheet->setCellValue("D" . $i, $v['login_code']);
                $worksheet->setCellValue("E" . $i, $startTime);
                $worksheet->setCellValue("F" . $i, $endTime);
                $worksheet->setCellValue("G" . $i, $startTime1);
                $worksheet->setCellValue("H" . $i, $endTime2);
                $i++;
            }
            $writer = new Xlsx($spreadsheet);
            $filename = date("YmdHis-") . '登录码.xlsx';
            $filePrefix = 'storage/file/';
            $filePath = $filePrefix . $filename;
            $fullPath = public_path() . $filePrefix;
            if (file_exists($fullPath . $filename)) {
                return $this->success(['file_path' => $filePath]);
            }
            if (!file_exists($fullPath)) {
                mkdir($fullPath, 0755);
            }
            $writer->save($fullPath . $filename);
            /* 释放内存 */
            $spreadsheet->disconnectWorksheets();
            unset($objSpreadsheet);

            return $this->success(['file_path' => $filePath, 'domain' => $this->request->domain()]);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 删除文件
     * @return \think\response\Json
     */
    public function removeFile()
    {
        try {
            if ($this->request->param('unlink_file_name')) {
                unlink(public_path() . $this->request->param('unlink_file_name'));
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}